# Chat session model
from datetime import datetime
from sqlalchemy import Column, BigInteger, Integer, String, Text, DateTime, Boolean, Enum, ForeignKey
from sqlalchemy.orm import relationship
from ..database import Base


class ChatSession(Base):
    __tablename__ = "chat_sessions"
    
    id = Column(BigInteger, primary_key=True, index=True, comment="会话ID")
    user_id = Column(BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, comment="用户ID")
    avatar_id = Column(BigInteger, ForeignKey("avatars.id", ondelete="CASCADE"), nullable=False, comment="数字人ID") 
    novel_id = Column(BigInteger, ForeignKey("novels.id", ondelete="SET NULL"), nullable=True, comment="小说ID")
    character_id = Column(BigInteger, ForeignKey("novel_characters.id", ondelete="SET NULL"), nullable=True, comment="扮演的角色ID")
    title = Column(String(200), nullable=True, comment="会话标题")
    topic = Column(String(100), nullable=True, comment="讨论话题")
    session_type = Column(
        Enum("discussion", "roleplay", "analysis", name="session_type_enum"),
        default="discussion",
        comment="会话类型"
    )
    context = Column(Text, nullable=True, comment="会话上下文")
    roleplay_context = Column(Text, nullable=True, comment="角色扮演背景设定")
    message_count = Column(Integer, default=0, comment="消息数量")
    last_message_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="最后消息时间")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
    is_active = Column(Boolean, default=True, comment="是否激活")
    
    # 关系
    user = relationship("User", back_populates="chat_sessions")
    avatar = relationship("Avatar", back_populates="chat_sessions") 
    # novel = relationship("Novel", back_populates="chat_sessions")
    # character = relationship("NovelCharacter", back_populates="chat_sessions")
    messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan") 